package com.example.springboottest.example.netty.kyro;

import com.example.springboottest.student.model.Student;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Date;


public class KyroTransferClient {
    private String host;
    private int port;
    private Student message;

    public KyroTransferClient(String host, int port, Student message) {
        this.host = host;
        this.port = port;
        this.message = message;
    }

    public void send() throws InterruptedException {

        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();

        try {
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new KyroStudentEncoder(),
                                    new KyroStudentDecoder(),
                                    new KyroClientHandler(message));
                        }
                    });

            ChannelFuture future = bootstrap.connect(host, port).sync();

            future.channel().closeFuture().sync();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {

        Student message = new Student("001", "jack", 21, "北京市");

        while (true) {
            new KyroTransferClient("localhost", 8000, message).send();
            Thread.sleep(5000);
        }
    }
}